<?php
namespace Admin\Model;

class CategoryModel extends CommonModel{
	protected $fields = array("id","c_name","parent_id","isrec");
	protected $_validate = array(
		//array(验证字段1,验证规则,错误提示,[验证条件,附加规则,验证时间]),
		array("c_name","require","分类名称必填"),
	);
	//getCateTree 获取格式化之后的数据
	public function getCateTree($id=0){
		$data = $this->select();
		$list = $this->getTree($data,$id);
		return $list;
	}
	//获取某个父分类下的所有子分类的id标识
	public function getChildren($id=0){
		$data = $this->select();
		$list = $this->getTree($data,$id,1,true);
		foreach ($list as $key => $value) {
			$tree[] = $value["id"];
		}
		return $tree;
	}
	//getTree 递归 格式化信息
	public function getTree($data,$id=0,$lev=1,$is_static=false){
		static $list = [];
		if($is_static){
			$list = [];
		}
		foreach ($data as $key => $value) {
			if($value["parent_id"] == $id){
				$value["lev"] = $lev;
				$list[] = $value;
				$this->getTree($data,$value["id"],$lev+1);
			}
		}
		return $list;
	}
	public function dels($id){
		//有子分类不许删除
		$res = $this->where("parent_id=".$id)->find();
		if($res){
			return false;
		}
		return $this->where("id=".$id)->delete();
	}
	public function update($data){
		//不许父分类修改到子分类 手机->苹果手机
		//获取所有的子分类
		$seed_category = $this->getCateTree($data["id"]);
		foreach ($seed_category as $key => $value) {
			if($data["id"] == $seed_category["parent_id"]){
				return false;
			}
		}
		return $this->save();
		//$this->where()->save(); // 根据条件更新记录
	}
}

?>